#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/word-search/

class Solution {
    int m, n, len;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool check[10][10];
public:
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size(), n = board[0].size(), len = word.size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {
                    check[i][j] = true;
                    if (dfs(board, word, i, j, 1) == true) return true;
                    check[i][j] = false;
                }
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>>& board, string word, int row, int col, int Idx)
    {
        if (Idx == len) return true;

        for (int z = 0; z < 4; z++)
        {
            int x = dx[z] + row, y = dy[z] + col;
            if (x >= 0 && x < m && y >= 0 && y < n && !check[x][y] && board[x][y] == word[Idx])
            {
                check[x][y] = true;
                if (dfs(board, word, x, y, Idx + 1) == true) return true;
                check[x][y] = false;
            }
        }

        return false;
    }
};